<template>
  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      width="40%"
      @close="handleClose"
  >
    <el-form ref="ruleFormRef" :model="formVal" :rules="rules" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formVal.username"/>
      </el-form-item>
      <el-form-item v-if="dialogTitle==='添加用户'" label="密码" prop="password">
        <el-input v-model="formVal.password" type="password"/>
      </el-form-item>
      <el-form-item label="邮件" prop="email">
        <el-input v-model="formVal.email"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formVal.mobile"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 接收传递来的属性值
import {addUser, editUser} from "@/api/users.js";
import i18n from "@/i18n/index.js";

const props = defineProps(["dialogVisible", "dialogTitle", "dialogTableValue"])
// 定义v-model的自动化事件,与前面定义的值对应
const myEmit = defineEmits(["update:model-value", "initUserList"])

const ruleFormRef = ref()
// 表单信息
const form = reactive({
  username: "ZTest0",
  password: "123456",
  email: "123@abc.com",
  mobile: "987654321",
})

const formVal = computed(() => {
  form.value = props.dialogTableValue
  return form.value
})

// 点击关闭按钮
const handleClose = () => {
  myEmit("update:model-value", false)
}

// 点击确定按钮
const handleConfirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      props.dialogTitle === "添加用户" ? addUser(form) : editUser(form)
      ElMessage({
        message: i18n.global.t("message.updateSuccess"),
        type: 'success',
      })
      myEmit("initUserList")
    } else {
      console.log('error submit!', fields)
    }
  })
  handleClose()
}

// 表单校验规则
const rules = reactive({
  username: [
    {required: true, message: 'Please input Activity name', trigger: 'blur'},
  ],
  password: [
    {required: true, message: 'Please input Activity name', trigger: 'blur'},
  ],
  email: [
    {type: "email", message: 'Please input correct email address', trigger: ['blur', 'change']},
  ],
  mobile: [
    {required: true, message: 'Please input Activity name', trigger: 'blur'},
  ],
})
</script>

<style lang="scss" scoped>

</style>